<template>
  <div class="container">
    <!-- 固定导航 -->
    <van-nav-bar fixed title="小冰"></van-nav-bar>

    <!-- 聊天主体区域 -->
    <div class="chat-list">
      <div v-for="(obj, index) in list" :key="index">
        <!-- 左侧是机器人小思 -->
        <div class="chat-item left" v-if="obj.name !== 'me'">
          <van-image fit="cover" round src="http://chenziyu.xyz/image/5.jpg" />
          <div class="chat-pao">{{ obj.msg }}</div>
        </div>

        <!-- 右侧是当前用户 -->
        <div class="chat-item right" v-else>
          <div class="chat-pao">{{ obj.msg }}</div>
          <van-image fit="cover" round :src="pathFilter(meImage) || log" />
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field v-model="word" placeholder="说点什么...">
        <template #button>
          <span style="font-size: 12px; color: #333" @click="sendFn">发送</span>
        </template>
      </van-field>
    </div>
    <audio src="@/assets/mp3/message.mp3" ref="audio"></audio>
  </div>
</template>

<script>
// 导入 socket.io-client 包
import { io } from "socket.io-client";
import { getToken } from "@/utils/token";
import { getUser } from "@/api";
import { pathFilter } from '@/utils/filter'
import log from '@/assets/image/log.png'
export default {
  name: "Chat",
  data() {
    return {
      log,
      meImage: '',
      word: "我是编程小王子", // 输入框的内容
      // 所有的聊天消息
      list: [
        // 只根据 name 属性，即可判断出这个消息应该渲染到左侧还是右侧
        { name: "xs", msg: "hi，你好！我是小冰" },
        // { name: "me", msg: "我是编程小王子" },
      ],
      socket: null, // 客户端和服务器端建立链接的socket对象
    };
  },
  async created() {

    try {
      const res = await getUser();
      // this.$store.commit('setUser',res.data);
      this.meImage = res.data.photo;
    } catch (error) {

    }
    // 创建客户端 websocket 的实例
    this.socket = io("http://chenziyu.xyz:8000", {
      query: {
        token: getToken(),
      },
      transports: ["websocket"],
    });
    // 测试下是否建立链接成功
    // this.socket.on("connect", () => {
    //   console.log("链接建立成功");
    // });

    // 接收后端传回来的消息
    this.socket.on("message", (obj) => {
      this.$refs.audio.play();
      // 理解组织相同字段对象放到数组里 -> v-for更新
      this.list.push({
        name: "xs",
        msg: obj.msg,
      });
      // 滚动到底部
      this.scrollToBottom();
    });
    this.sendFn();
  },

  methods: {
    pathFilter,
    sendFn() {
      // 发送span->点击事件
      if (this.word.trim().length === 0) return;
      // 用socket链接对象.emit('后端接收消息的事件名', 值)
      this.socket.emit("message", {
        msg: this.word,
        timestamp: new Date().getTime(),
      });
      // 把消息显示到页面上
      this.list.push({
        msg: this.word,
        name: "me",
      });

      // 滚动到底部
      this.scrollToBottom();

      // 清空输入框
      this.word = "";
    },
    // 滚动到页面底部
    scrollToBottom() {
      try {
        // 最后一条聊天消息滚动到屏幕范围
        // 数据变化->DOM更新是异步的, 所以获取到的是上一条div
        this.$nextTick(() => {
          // 获取到最后一项对应的 DOM 元素
          const theDiv = document.querySelector(".chat-list>div:last-child");
          // 调用 scrollIntoView() 方法，显示这个元素
          theDiv?.scrollIntoView({
            behavior: "smooth", // 动画平滑
          });
        });
      } catch (error) { }
    },
  },
  // 组件被销毁之前，清空 sock 对象
  beforeDestroy() {
    // 关闭连接
    this.socket.close();
    // 销毁 websocket 实例对象
    this.socket = null;
  },
  activated() {
    this.scrollToBottom();
  }
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 100px 0;

  .chat-list {
    height: 100%;
    overflow-y: scroll;

    .chat-item {
      padding: 10px;

      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }

      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;

        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}

.chat-item.right {
  text-align: right;

  .chat-pao {
    margin-left: 0;
    margin-right: 15px;

    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}

.chat-item.left {
  text-align: left;

  .chat-pao {
    margin-left: 15px;
    margin-right: 0;

    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}

.reply-container {
  position: fixed;
  left: 0;
  bottom: 50px;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}</style>
